//permission.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserService } from '../user/user.service';
import { ApiException } from '../common/filter/http-exception/api.exception';
import { ApiErrorCode } from '../common/enums/api-error-code.enum';
import { JWT_User } from '../auth/dto/update-auth.dto';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private userService: UserService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    interface CusRequest extends Request {
      user?: JWT_User;
    }
    const request: CusRequest = context.switchToHttp().getRequest();
    const user = request.user;
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(
      'permissions',
      [context.getClass(), context.getHandler()],
    );
    if (
      !requiredPermissions ||
      (requiredPermissions && requiredPermissions.length === 0)
    ) {
      return true;
    }

    if (!user) {
      throw new ApiException('请先登录', ApiErrorCode.USER_ID_INVALID);
    }
    // 判断用户是否有权限
    const permissionNames = await this.userService.findPermissionNames(user);
    const isContainedPermission = requiredPermissions.every((item) =>
      permissionNames.includes(item),
    );
    if (!isContainedPermission) {
      throw new ApiException('权限不足', ApiErrorCode.ROLE_EXIST);
    }

    return true;
  }
}
